package com.zy

import java.text.MessageFormat

import scala.io.Source.fromFile

/**
 * @description: 测试
 * @author: yizhao
 * @create: 2020-04-22 20:53
 **/
object Chapter2 {

  def main(args: Array[String]): Unit = {

    println(raw"\n 不会转义 \t hello")
    println("\n 会转义 \t  hello")

    //to和until的区别
    for (i <- 1 to 3) {
      print(i) //1 2 3
    }

    val str = "abc"
    for (i <- 0 until str.length) {
      print(str.charAt(i)) //abc
      //print(i) //012
    }

    //直接便利
    for (i <- "def") {
      print(s"$i , ") //d , e , f ,
    }

    //for 推导式
    val arr = for (i <- 1 to 20) yield i % 3
    println(arr)

    //嵌套for循环 可以这样写
    for (i <- 1 to 3; ii <- 10 to 15) {
      print(s"($i , $ii )")
    }
    println()
    //上面等价于下面这个
    for (i <- 1 to 3) {
      for (ii <- 10 to 15) {
        print(s"( $i , $ii )")
      }
    }

    //嵌套for循环 还可以加条件
    for (i <- 1 to 3; ii <- 1 to 3 if i != ii) {
      print(s"( $i , $ii )")
    }
    println()
    //引入循环中使用的变量
    for (i <- 1 to 3; n = 10 - i; ii <- n to 10) {
      print(s"（$i , $ii ）")
    }

    println()
    println(recursion(4))
    println(sum(1, 2))
    println(sum(1, 2, 3, 4, 6))
    //告诉当做序列处理Seq
    println(sum(1 to 10: _*))
    println(recursionSum(1, 2, 3, 4, 5))

    //调用java方法，原java方法参数是Object，调用时非字符串需要使用 1.asInstanceOf[AnyRef]
    //val aa = MessageFormat.format("hello {0} {2} ","word",1.asInstanceOf[AnyRef])
    val aa = MessageFormat.format("hello {0} {1} ", "word", true.asInstanceOf[AnyRef])
    println(aa)

    //懒值首次调用时才初始化, 用于开销较大的初始化语句
    lazy val strFile = fromFile("D:\\imsdk_20200418.log")
    println(strFile.mkString)
    strFile.close()


  }

  def aa(int: Int) = int % 2 == 0

  //递归函数必须给定返回值
  def recursion(n: Int): Int = if (n > 1) n * recursion(n - 1) else 1

  //可边长参数
  def sum(nums: Int*): Int = {
    for (num <- nums) {
      print(s"num= $num, ")
    }
    nums.sum
  }

  def recursionSum(nums: Int*): Int = {
    //_* 转换成seq 后面会再讲
    if (nums.isEmpty) 0 else nums.head + recursionSum(nums.tail: _*)
  }


}
